package com.web.exiaodao.remote.service.impl;

import com.web.exiaodao.business.entity.VSDCExperience;
import com.web.exiaodao.remote.vo.VSDCExperienceVo;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.repository.VSDCExperienceRepository;
import com.web.exiaodao.remote.service.ApiVSDCExperienceService;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;

/**
 * @author: zhangl
 * @times: 2016-11-13 19:59:26
 * 类的说明：前端APIVSDCExperience接口实现类
 **/
@Service("ApiVSDCExperienceService")
@Transactional(readOnly = false)
public class ApiVSDCExperienceServiceImpl extends BaseService<VSDCExperience> implements ApiVSDCExperienceService {

    private static final Logger LOGGER = Logger.getLogger(ApiVSDCExperienceServiceImpl.class);

    @Autowired
    VSDCExperienceRepository vSDCExperienceRepository;

    @Override
    public XaResult<VSDCExperienceVo> findOne(Long tId) throws BusinessException {
        VSDCExperience obj = vSDCExperienceRepository.findByIdAndStatusNot(tId, XaConstant.Status.delete);
        XaResult<VSDCExperienceVo> xr = new XaResult<VSDCExperienceVo>();
        if (XaUtil.isNotEmpty(obj)) {
            xr.setObject(JSON.parseObject(JSON.toJSONString(obj), VSDCExperienceVo.class));
            xr.getObject().setId(obj.getId());
            LOGGER.info("查询单个实体----->VSDCExperience");
        } else {
            xr.error(XaConstant.Message.object_not_find);
            LOGGER.info(XaConstant.Message.object_not_find);
        }
        return xr;
    }

    @Override
    public XaResult<VSDCExperienceVo> findLastOne() throws BusinessException {
        XaResult<VSDCExperienceVo> xr = new XaResult<>();
        Map<String, SearchFilter> filters = new HashMap<>();
        filters.put("status", new SearchFilter("status", Operator.NE, XaConstant.Status.delete));
        List<VSDCExperience> entitys = vSDCExperienceRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), VSDCExperience.class), new Sort(
                new Sort.Order[]{
                        new Sort.Order(Sort.Direction.DESC, "createTime"),
                        new Sort.Order(Sort.Direction.DESC, "id")
                }));
        if (entitys == null || entitys.size() == 0) {
            xr.error("暂无信息");
        } else {
            xr.setObject(JSON.parseObject(JSON.toJSONString(entitys.get(0)), VSDCExperienceVo.class));
            xr.getObject().setId(entitys.get(0).getId());
            LOGGER.info("查询单个实体----->VSDCExperience");
        }
        return xr;
    }


    @Override
    public XaResult<List<VSDCExperienceVo>> findListNEStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable)
            throws BusinessException {
        XaResult<List<VSDCExperienceVo>> xr = new XaResult<>();
        StringBuffer csql = new StringBuffer("");
        csql.append(" SELECT ex.id, ex.vsdc_state, ex.vsdc_id, ex.user_id, ex.joni_date, vs.vsdc_introduce FROM tb_xa_vsdcexperience ex LEFT JOIN tb_xa_vsdc vs ON ex.vsdc_id = vs.id ");
        if (XaUtil.isNotEmpty(status)) {
            csql.append( (csql.toString().contains("WHERE") ? " AND " : " WHERE ") + " ex.status <>  " + status.intValue());
        }
        if (filterParams.containsKey("EQ_userId")) {
            csql.append( (csql.toString().contains("WHERE") ? " AND " : " WHERE ") + " ex.user_id = " + filterParams.get("EQ_userId"));
        }
        if (filterParams.containsKey("EQ_vSDC_State")) {
            csql.append( (csql.toString().contains("WHERE") ? " AND " : " WHERE ") + " ex.vsdc_state = " + filterParams.get("EQ_vSDC_State"));
        }
        csql.append(" order by ex.create_time desc ");
        List<VSDCExperienceVo> vos = new ArrayList<>();
        List<Object[]> objs = this.query(csql.toString(), pageable.getPageNumber() * pageable.getPageSize(), pageable.getPageSize());
        for (Object[] obj : objs) {
            VSDCExperienceVo vo = new VSDCExperienceVo();
            vo.setId(((BigInteger) obj[0]).longValue());//??
            vo.setVSDC_State(obj[1] != null ? Integer.parseInt(obj[1]+"") : -1);
            vo.setVSDC_Id(obj[2] != null ? ((BigInteger) obj[2]).longValue() : -1);
            vo.setUserId((String) obj[3]);
            vo.setJoniDate((String) obj[4]);
            vo.setVsdc_introduce((String) obj[5]);
            vos.add(vo);
        }
        xr.setObject(vos);
        LOGGER.info("分页查询实体集合----->义工经历");
        return xr;
    }

    @Override
    public XaResult<List<VSDCExperienceVo>> findListEQStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable)
            throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示正常数据
            status = XaConstant.Status.valid;
        }
        filters.put("status", new SearchFilter("status", Operator.EQ, status));
        Page<VSDCExperience> page = vSDCExperienceRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), VSDCExperience.class), pageable);
        XaResult<List<VSDCExperienceVo>> xr = new XaResult<List<VSDCExperienceVo>>();
        xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), VSDCExperienceVo.class));
        for (int i = 0; i < page.getContent().size(); i++) {
            xr.getObject().get(i).setId(page.getContent().get(i).getId());
        }
        return xr;
    }

    @Override
    public XaResult<VSDCExperienceVo> multiOperate(String modelIds,
                                                   Integer status) throws BusinessException {
        XaResult<VSDCExperienceVo> xr = new XaResult<VSDCExperienceVo>();
        if (status == null) {
            status = XaConstant.Status.delete;
        }
        if (modelIds != null) {
            String[] ids = modelIds.split(",");
            for (String id : ids) {
                VSDCExperience obj = vSDCExperienceRepository.findByIdAndStatusNot(Long.parseLong(id), status);
                if (XaUtil.isNotEmpty(obj)) {
                    obj.setStatus(status);
                    obj = vSDCExperienceRepository.save(obj);
                    xr.setObject(JSON.parseObject(JSON.toJSONString(obj), VSDCExperienceVo.class));
                    xr.getObject().setId(obj.getId());
                }
            }
        }
        LOGGER.info("更改数据状态----->VSDCExperience");
        return xr;
    }

    @Override
    public XaResult<VSDCExperienceVo> createModel(VSDCExperience model)
            throws BusinessException {
        XaResult<VSDCExperienceVo> xr = new XaResult<VSDCExperienceVo>();
        model.setVSDC_State(1);
        VSDCExperience obj = vSDCExperienceRepository.save(model);
        xr.setObject(JSON.parseObject(JSON.toJSONString(obj), VSDCExperienceVo.class));
        xr.getObject().setId(obj.getId());
        LOGGER.info("新增数据成功----->VSDCExperience");
        return xr;
    }

    @Override
    public XaResult<VSDCExperienceVo> updateModel(VSDCExperience model)
            throws BusinessException {
        VSDCExperience obj = vSDCExperienceRepository.findOne(model.getId());
        XaResult<VSDCExperienceVo> xr = new XaResult<VSDCExperienceVo>();
        if (XaUtil.isNotEmpty(obj)) {
            obj.setJoniDate(XaUtil.isNotEmpty(model.getJoniDate()) ? model.getJoniDate() : obj.getJoniDate());
            obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
            obj.setVSDC_Id(XaUtil.isNotEmpty(model.getVSDC_Id()) ? model.getVSDC_Id() : obj.getVSDC_Id());
            obj.setVSDC_State(XaUtil.isNotEmpty(model.getVSDC_State()) ? model.getVSDC_State() : obj.getVSDC_State());
            obj = vSDCExperienceRepository.save(obj);
            xr.setObject(JSON.parseObject(JSON.toJSONString(obj), VSDCExperienceVo.class));
            xr.getObject().setId(obj.getId());
        } else {
            xr.error(XaConstant.Message.object_not_find);
        }
        LOGGER.info("编辑数据成功----->VSDCExperience");
        return xr;
    }

}
